package controller

import (
	"bluebell/dao/redis"
	"bluebell/logic"
	"bluebell/models"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
)

// VoteHandler
// @Tags PantheonApi
// @Summary 投票
// @Schemes
// @Description	Post 请求, 参数在body中
// @Accept json
// @Produce json
// @Param	VoteDataForm body  models.VoteDataForm true "投票信息"
// @Success 200 {string} json{"code","message","data"}
// @Router	/api/Pantheon/vote [post]
func VoteHandler(c *gin.Context){
	// 参数校验,给哪个文章投什么票
	vote := new(models.VoteDataForm)
	if err := c.ShouldBindJSON(&vote); err != nil {
		errs, ok := err.(validator.ValidationErrors) // 类型断言
		if !ok {
			ResponseError(c, CodeInvalidParams)
			return
		}
		errData := removeTopStruct(errs.Translate(trans)) // 翻译并去除掉错误提示中的结构体标识
		ResponseErrorWithMsg(c, CodeInvalidParams, errData)
		return
	}
	// 获取当前请求用户的id
	userID, err := getCurrentUserId(c)
	if err != nil {
		ResponseError(c, CodeNotLogin)
		return
	}
	// 具体投票的业务逻辑
	if err := logic.VoteForPost(userID, vote); err != nil {
		zap.L().Error("logic.VoteForPost() failed", zap.Error(err))
		switch err {
		case redis.ErrVoteRepeated: // 重复投票
			ResponseError(c, ErrVoteRepeated)
		case redis.ErrorVoteTimeExpire: // 投票超时
			ResponseError(c, ErrorVoteTimeExpire)
		default:
			ResponseError(c, CodeServerBusy)
		}
		return
	}
	ResponseSuccess(c, nil)
}